<template>
	<div class="chat-list">
		<div v-for="(chat,key) in chats" :key="chat.id" @click="selectChat(chat,key)"
			:class="{ active: selectedChat && selectedChat.id === chat.id }">
			<span v-if="chat.unreadMessages > 0" class="unread-message">
				{{ chat.unreadMessages }}
			</span>
			<img :src="chat.avatar" alt="Avatar" class="avatar" />
			<div class="chat-info">
				<div class="name">{{ chat.name }}</div>
				<div class="last-message">{{ chat.lastMessage }}</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		getSocket
	} from 'utils/socketUtils.js';
	//socket实例
	import {
		socketInstance
	} from "utils/socketUtils.js"

	export default {
		data() {
			return {
				chats: [],
				selectedChat: null,
			}
		},
		onShow() {
			//连接socket
			socketInstance(uni.getStorageSync('Token'), uni.getStorageSync('username'));
			const scocket = getSocket();
			scocket.on('connect', () => { // 默认通道 connect是通道名称
				console.log('连接成功');
			});
			scocket.on('channel_user', (data) => { // 自定义通道 前后端约定
				console.log('message页面，监听到channel_user消息：');
				console.log(JSON.parse(data));
				const msgData = JSON.parse(data);
				this.chats.forEach((item, idx) => {
					if (item.id === msgData.senderId) {
						console.log(this.chats, "cddd")
						item.lastMessage = msgData.msgContent;
						item.unreadMessages += 1;
						// item.messages.push({
						// 	id: Date.now(),
						// 	type: 'received',
						// 	content: msgData.msgContent,
						// })

					}
				})
			});
			scocket.on('channel_system', (data) => { // 自定义通道
				console.log('监听到系统channel_system消息：');
				console.log(data);
			});
			scocket.on('disconnect', () => { // 默认通道
				console.log('断开连接');
			});
			//查找最新一条聊天记录
			console.log(this.$globalData.extraParam, "hhhh");
			this.getCurrentChat(this.$globalData.extraParam)

		},
		mounted() {
			this.getAlluser();
		},
		methods: {
			getAlluser() {
				uni.request({
					// 接口地址
					url: '/dev-api/system/user/allUserlist',
					method: "get",
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('Token'),
						'Content-Type': 'application/json;charset=utf-8'
					},
					success: res => {
						console.log(res, "用户接口")
						//过滤出自己
						let result = res.data.data.filter(item => item.userId != uni.getStorageSync('userInfo')
							.userId);
						this.chats = result.map((item) =>
							({
								id: item.userId,
								name: item.userName,
								avatar: "http://localhost:8080" + item.avatar,
								lastMessage: '',
								messages: [],
								unreadMessages: 0
							})
						)
						//查询当前用户的接收的消息列表
						uni.request({
							url: '/dev-api/system/sendMsg/listByReceiverId',
							method: "post",
							data: {
								receiverIds: uni.getStorageSync('userInfo').userId + ""
							},
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('Token'),
								'Content-Type': 'application/json;charset=utf-8'
							},
							success: res => {
								console.log(res.data, "dddd")
								const currentUserMsg = res.data || [];
								this.chats.forEach(item => {
									currentUserMsg.forEach(msgItem => {
										if (item.id == msgItem.senderId) {
											// item.lastMessage = msgItem
											// 	.messageContent;
											if (msgItem.isRead == 0) {
												item.unreadMessages += 1;
											}
										}
									})
								})
							}
						})

						this.chats.forEach(item => {
							this.getCurrentChat(item.id);
						})

					}
				})
			},
			selectChat(chat, key) {
				this.selectedChat = chat;
				console.log(chat, "chatttt");
				//设置该用户聊天信息为已读
				uni.request({
					url: '/dev-api/system/sendMsg/updateMsgRead',
					method: "post",
					data: {
						receiverIds: uni.getStorageSync('userInfo').userId + "",
						senderId: chat.id
					},
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('Token'),
						'Content-Type': 'application/json;charset=utf-8'
					},
					success: res => {
						console.log(res, "消息标记为已读")
					}
				})

				// 跳到聊天页面
				uni.navigateTo({
					url: '/pages/chatWindow/index?selectedChat=' + encodeURIComponent(JSON.stringify(chat))
				});
				this.chats[key].unreadMessages = 0;
			},
			getCurrentChat(chatId) {
				//查询当前聊天窗口的聊天记录
				uni.request({
					url: '/dev-api/system/sendMsg/listBychatId',
					method: "post",
					data: {
						receiverIds: uni.getStorageSync('userInfo').userId + "",
						senderId: chatId
					},
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('Token'),
						'Content-Type': 'application/json;charset=utf-8'
					},
					success: res => {
						console.log(res.data, "聊天记录")
						const chatArr = res.data || [];
						if (chatArr.length > 0) {
							let lastMsa = chatArr.pop();
							this.chats.forEach(item => {
								if (item.id == chatId) {
									item.lastMessage = lastMsa.messageContent;
								}
							})
						}
					}
				})

			}


		}
	}
</script>
<style scoped>
	.chat-list {
		display: flex;
		flex-direction: column;
	}

	.unread-message {
		position: absolute;
		/* top: 2px; */
		left: 45px;
		background-color: red;
		color: white;
		border-radius: 50%;
		padding: 2px 5px;
		font-size: 12px;
	}

	.chat-list div {
		display: flex;
		align-items: center;
		padding: 10px;
		cursor: pointer;
	}

	.chat-list div.active {
		background-color: #f0f0f0;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.chat-info {
		display: flex;
		flex-direction: column;
	}

	.name {
		font-weight: bold;
	}

	.last-message {
		color: #999;
	}
</style>